package top.lenjon.lib.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import top.lenjon.lib.entity.BookClassify;
import top.lenjon.lib.model.ResponseModel;
import top.lenjon.lib.service.impl.BookClassifyServiceImpl;
import top.lenjon.lib.service.impl.BookServiceImpl;

/**
 * @author wei
 * @since 2020/11/10 9:41
 */
@RestController
@RequestMapping("/book")
@CacheConfig(cacheNames = "book")
public class BookController {
    @Autowired
    private BookServiceImpl bookService;

    @Autowired
    private BookClassifyServiceImpl bookClassifyService;

    /**
     * 获取书本总数数量
     *
     * @return
     */
    @GetMapping("/getSum")
    public ResponseModel getBookCount() {
        return ResponseModel.success("success", bookService.getBooks(null, null).size());
    }

    /**
     * 获取图书
     *
     * @param pageIndex 分页页码，从0开始
     * @param pageNum   每页的记录数，允许为空，为null时返回所有记录
     * @return 书本信息
     */
    @Cacheable(key = "#root.methodName+#pageNum")
    @GetMapping("/getBooks")
    public ResponseModel getBooks(Integer pageIndex, Integer pageNum) {
        return ResponseModel.success("success", bookService.getBooks(pageIndex, pageNum));
    }

    /**
     * 获取某本书的分类
     *
     * @param bookId bookId
     * @return 书本分类
     */
    @GetMapping("/getBookClassifies")
    public ResponseModel getClassifyByBookId(int bookId) {
        BookClassify classify = bookClassifyService.getById(bookId);
        if (classify == null) {
            return ResponseModel.error("书本不存在");
        } else {
            return ResponseModel.success("success", classify);
        }
    }

    /**
     * 分类查询
     *
     * @param classify 类别，只需要提供要筛选的分类，并且为true
     * @return 查询到的记录
     */
    @Cacheable(key = "#classify.toString()")
    @PostMapping("/getBookByClassify")
    public ResponseModel getBookByClassify(@RequestBody BookClassify classify) {
        System.out.println(classify);

        return ResponseModel.success("success", bookService.getBooksByClassify(classify));
    }

    /**
     * 按标题模糊查找
     * @param title 标题
     * @return 查询到的记录
     */
    @Cacheable(key = "#title")
    @GetMapping("/getBookByTitle")
    public ResponseModel getBookByTitle(String title) {
        return ResponseModel.success("success", bookService.getBooksByTitle(title));
    }

    @GetMapping("getBookById")
    public ResponseModel getBookById(int id){
        return ResponseModel.success("success",bookService.getById(id));
    }

}
